package com.graduate.examapp.view.customview

import android.content.Context
import android.graphics.ColorFilter
import android.widget.TextView
import androidx.appcompat.content.res.AppCompatResources
import androidx.core.content.ContextCompat
import com.airbnb.lottie.LottieAnimationView
import com.airbnb.lottie.LottieProperty
import com.airbnb.lottie.SimpleColorFilter
import com.airbnb.lottie.model.KeyPath
import com.airbnb.lottie.value.LottieValueCallback
import com.google.android.material.tabs.TabLayout
import com.graduate.examapp.R
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.launch

/**
 * 选中状态
 */
fun  TabLayout.Tab.setSelected(context: Context) {
    this.customView?.let {
        //val textView = it.findViewById<TextView>(R.id.tab_text)
        //val selectedColor = ContextCompat.getColor(context, R.color.master)
        //textView.setTextColor(selectedColor)
        //val imageView = it.findViewById<LottieAnimationView>(R.id.tab_image)

        val lottieAnimationView = it.findViewById<LottieAnimationView>(R.id.tab_image)
        if (!lottieAnimationView.isAnimating) {
            lottieAnimationView.playAnimation()
        }
        val textView = it.findViewById<TextView>(R.id.tab_text)
        textView.setTextColor(ContextCompat.getColor(context, R.color.master))
        setLottieColor(lottieAnimationView, true, context)
    }
}

/**
 * 未选中状态
 */
fun TabLayout.Tab.setUnselected(context: Context) {
    this.customView?.let {
        //val textView = it.findViewById<TextView>(R.id.tv_tab_text)
        //val unselectedColor = ContextCompat.getColor(this@TabLayoutActivity, R.color.black)
        //textView.setTextColor(unselectedColor)

        val lottieAnimationView = it.findViewById<LottieAnimationView>(R.id.tab_image)

        if (lottieAnimationView.isAnimating) {
            //不能在主线程中播放动画
            lottieAnimationView.cancelAnimation()
            lottieAnimationView.progress = 0f // 还原初始状态
        }
        val textView = it.findViewById<TextView>(R.id.tab_text)
        textView.setTextColor(ContextCompat.getColor(context, R.color.black))
        setLottieColor(lottieAnimationView, false, context)
    }
}

/**
 * set lottie icon color
 */
private fun setLottieColor(imageView: LottieAnimationView?, isSelected: Boolean, context: Context) {
    imageView?.let {
        val color = if (isSelected) R.color.master else R.color.black
        val csl = AppCompatResources.getColorStateList(context, color)
        val filter = SimpleColorFilter(csl.defaultColor)
        val keyPath = KeyPath("**")
        val callback = LottieValueCallback<ColorFilter>(filter)
        it.addValueCallback(keyPath, LottieProperty.COLOR_FILTER, callback)
    }
}